/*******************************************************************
 * Copyright (c) 2013 珠海比特讯科技有限公司. All rights reserved.
 * （1）软件的版权将受到法律保护，不允许非经授权的使用；
 * （2）未经版权所有人授权，任何人不得修改、复制和传播软件源代码、图片及其它资源等；
 * （3）未经版权所有人授权，不允许对软件进行修改；
 * （4）未经版权所有人授权，不允许在该软件的基础上开发新的软件；
 * （5）珠海比特讯科技有限公司拥有最终解释权
 *******************************************************************/
package youxiao.bytezon.controllers;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import youxiao.bytezon.models.Teacher;
import youxiao.bytezon.models.TeacherLessonPremium;
import youxiao.bytezon.models.TeacherSalary;
import youxiao.bytezon.repositories.TeacherLessonPremiumRepository;
import youxiao.bytezon.repositories.TeacherSalaryRepository;
import youxiao.bytezon.views.commons.PageListView;
import youxiao.bytezon.views.teacher_lesson_premiums.TeacherLessonPremiumView;
import youxiao.bytezon.views.teacher_salaries.TeacherSalaryView;

@RestController
@RequestMapping("/teacher_salaries")
public class TeacherSalariesController extends BaseController {
	
	@Autowired TeacherSalaryRepository teacherSalaryRepository;
	@Autowired TeacherLessonPremiumRepository teacherLessonPremiumRepository;
	@Autowired EntityManager entityManager;
	
	@ResponseBody
	@RequestMapping(value = "", method = RequestMethod.GET)
	public PageListView<TeacherSalaryView> index(HttpServletRequest request) {
		String pageNumStr = request.getParameter("page");
		int pageNum = pageNumStr == null? 0 : Integer.parseInt(pageNumStr) - 1;
		Teacher currentTeacher = getCurrentTeacher();
		
		Pageable pageable = new PageRequest(pageNum, 50);
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		
    CriteriaQuery<TeacherSalary> cq = cb.createQuery(TeacherSalary.class);
    Root<TeacherSalary> root = cq.from(TeacherSalary.class);
    root.fetch("school");
    
    cq.select(root)
    		.where(cb.equal(root.<Teacher>get("teacher"), currentTeacher))
    		.orderBy(cb.desc(root.get("beginDate")));
		List<TeacherSalary> list = entityManager.createQuery(cq).setFirstResult(pageable.getOffset()).setMaxResults(pageable.getPageSize()).getResultList();
		
		// query the count of users
		CriteriaQuery<Long> queryCount = cb.createQuery(Long.class);
		queryCount.select(cb.count(queryCount.from(TeacherSalary.class)));
		queryCount.where(cb.equal(root.<Teacher>get("teacher"), currentTeacher));
		Long count = entityManager.createQuery(queryCount).getSingleResult();
		
		Page<TeacherSalary> page = new PageImpl<TeacherSalary>(list, pageable, count);
		return new PageListView<TeacherSalaryView>(page, entry -> new TeacherSalaryView(entry));
	}
	
	@ResponseBody
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	public TeacherSalaryView detail(@PathVariable("id") Long id) {
		TeacherSalary teacherSalary = teacherSalaryRepository.findOne(id);
		TeacherSalaryView teacherSalaryView = new TeacherSalaryView(teacherSalary);
		
		List<TeacherLessonPremium> premiumList = teacherLessonPremiumRepository.findAllByBillingDate(teacherSalary.getTeacher().getId(), teacherSalary.getBeginDate(), teacherSalary.getEndDate());

		Set<TeacherLessonPremiumView> teacherLessonPremiums = premiumList.stream()
				.map(entry -> new TeacherLessonPremiumView(entry))
				.collect(Collectors.toSet());
		
		teacherSalaryView.setTeacherLessonPremiums(teacherLessonPremiums);
		
		return teacherSalaryView;
	}
	
}
